<template>
    <!-- 用户管理 -->
  <div class="box">
      <!-- 头部搜索框 -->
      <el-card class="box-card">
          <el-form :inline="true" :model="paramsState">
              <el-form-item>
                  <el-input v-model="paramsState.username" size="small" placeholder="用户名"></el-input>
              </el-form-item>
              <el-form-item>
                  <el-button type="primary" size="small" @click="serach">查询</el-button>
              </el-form-item>
              <el-form-item>
                  <el-button size="small" @click="resetSearch">清空</el-button>
              </el-form-item>

          </el-form>
      </el-card>
      <!-- 底部表格 -->
      <el-card class="box-card">
          <el-form :inline="true">
              <el-form-item>
                  <el-button type="primary" size="small" @click="showAddUser">添加</el-button>
              </el-form-item>
              <el-form-item>
                  <el-button type="danger" size="small" @click="213">批量删除</el-button>
              </el-form-item>
          </el-form>
          <!-- 表格 -->
          <el-table :data="tableState.users" border style="width: 100%">
              <el-table-column type="selection" prop="date" width="50" align="center">
              </el-table-column>
              <el-table-column type="index" label="序号" align="center">
              </el-table-column>
              <el-table-column prop="username" label="用户名" align="center">
              </el-table-column>
              <el-table-column prop="nickName" label="用户昵称" align="center">
              </el-table-column>
              <el-table-column prop="roleName" label="角色列表" align="center">
              </el-table-column>
              <el-table-column prop="gmtCreate" label="创建时间" align="center">
              </el-table-column>
              <el-table-column prop="gmtModified" label="更新时间" align="center">
              </el-table-column>
              <!-- 底部表格操作部分 -->
              <el-table-column prop="address" fixed="right" label="操作" align="center" width="220px">
                  <template v-slot="{ row }">
                      <el-button type="info" icon="el-icon-user-solid" size="small" @click="showAssignRole(row)" />
                      <el-button type="primary" icon="el-icon-edit-outline" size="small"
                          @click="showUpdateUser(row)" />
                      <el-button type="danger" icon="el-icon-delete" size="small" @click="removeUser(row.id)" />
                  </template>
              </el-table-column>
          </el-table>
          <el-pagination :page-size="paramsState.limit" :current-page="paramsState.page"
              @current-change="handleCurrentChange" layout="prev, pager, next" :total="tableState.total">
          </el-pagination>
      </el-card>
      <!-- 添加用户的弹出框 -->
      <el-dialog :visible.sync="userState.dialogUserVisible" title="添加用户">
          <el-form :model="userState.user">
              <el-form-item label="用户名" required :label-width="formLabelWidth">
                  <el-input v-model="userState.user.username"></el-input>
              </el-form-item>
              <el-form-item label="用户昵称" required :label-width="formLabelWidth">
                  <el-input v-model="userState.user.nickName"></el-input>
              </el-form-item>
              <el-form-item label="用户密码" v-if="!userState.user.id" required :label-width="formLabelWidth">
                  <el-input v-model="userState.user.password"></el-input>
              </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="addOrUpdate">保 存</el-button>
          </div>
      </el-dialog>
      <!-- 修改用户的弹出框 -->
      <el-dialog :visible.sync="userState.dialogUserVisible2" title="修改用户">
          <el-form :model="userState.user">
              <el-form-item label="用户名" required :label-width="formLabelWidth">
                  <el-input v-model="userState.user.username"></el-input>
              </el-form-item>
              <el-form-item label="用户昵称" required :label-width="formLabelWidth">
                  <el-input v-model="userState.user.nickName"></el-input>
              </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="addOrUpdate2">保 存</el-button>
          </div>
      </el-dialog>
      <!-- 角色列表界面 -->
      <el-dialog title="设置角色" v-model="roleState" :visible.sync="roleState.dialogRoleVisible"
          :before-close="resetRoleData">
          <el-form label-width="80px">
              <el-form-item label="用户名">
                  <el-input disabled :value="userState.user.username"></el-input>
              </el-form-item>

              <el-form-item label="角色列表">
                  <el-checkbox :indeterminate="roleState.isIndeterminate" v-model="roleState.checkAll"
                      @change="handleCheckAllChange">全选</el-checkbox>
                  <div style="margin: 15px 0"></div>
                  <el-checkbox-group v-model="roleState.userRoleIds" @change="handleCheckedChange">
                      <el-checkbox v-for="role in roleState.allRoles" :key="role.id" :label="role.id">{{ role.roleName
                      }}</el-checkbox>
                  </el-checkbox-group>
              </el-form-item>
          </el-form>
          <template #footer>
              <el-button type="primary" @click="assignRole">保存</el-button>
              <el-button @click="resetRoleData">取消</el-button>
          </template>
      </el-dialog>
  </div>
</template>

<script>
import {
  getUserListApi,
  saveOrUpdateUserApi,
  getUserRoleListApi,
  assignUserRoleListApi,
  removeUserApi,
  removeUsersApi,
} from "@/api/acl/user"

export default {
  name: "User",
  data() {
      return {
          paramsState: {
              username: "",
              searchUsername: "",
              page: 1, // 当前页码
              limit: 7, // 每页数量
              total: 20,
          },
          tableState: {
              total: 0,
              users: [],
              selectedIds: [],
          },
          pageCount: 6,
          //用户状态
          userState: {
              dialogUserVisible: false,
              dialogUserVisible2: false,
              userLoading: false,
              user: {
                  username: "",
                  nickName: "",
                  password: "",
              },
          },
          formLabelWidth: '120px',
          roleState: {
              dialogRoleVisible: false,
              roleLoading: false,
              checkAll: false,
              isIndeterminate: false,
              userRoleIds: [],
              allRoles: [],
          }
      }
  },
  methods: {
      handleCurrentChange(size) {
          this.paramsState.page = size
          this.getUsers(size)
      },
      //获取用户列表
      async getUsers(page = this.paramsState.page, limit = this.paramsState.limit) {
          this.paramsState.page = page;
          this.paramsState.limit = limit;
          const result = await getUserListApi(page, limit, {
              username: this.paramsState.searchUsername,
          });
          const items = result.data.items
          const total = result.data.total;
          this.tableState.users = items;
          this.tableState.total = total;
          this.tableState.selectedIds = [];
          // console.log("first", result)
      },
      // 根据输入进行搜索
      serach() {
          this.paramsState.searchUsername = this.paramsState.username;
          this.getUsers(1);
      },
      // 重置输入后搜索
      resetSearch() {
          this.paramsState.searchUsername = "";
          this.paramsState.username = "";
          this.getUsers(1);
      },
      //显示添加用户界面
      showAddUser() {
          this.userState.user = {
              username: "",
              nickName: "",
              password: "",
          };
          this.userState.dialogUserVisible = true;
      },
      //取消用户保存或更新
      cancel() {
          this.userState.dialogUserVisible = false;
          this.userState.user = {
              username: "",
              nickName: "",
              password: "",
          };
      },
      //保存新用户
      async addOrUpdate() {
          //判断用户名是不是admin
          if (this.userState.user.username === "admin") {
              alert("admin账号不能添加或更新");
              return;
          }
          try {
              await saveOrUpdateUserApi(this.userState.user);
              this.getUsers(1);
              this.userState.user = {
                  username: "",
                  nickName: "",
                  password: "",
              };
              this.userState.dialogUserVisible = false;
              this.userState.dialogUserVisible2 = false;
          } catch (error) {
              this.userState.dialogUserVisible = false;
              this.userState.dialogUserVisible2 = false;
              console.log(error)
          }
      },
      //更新用户
      async addOrUpdate2() {
          //判断用户名是不是admin
          if (this.userState.user.username === "admin") {
              alert("admin账号不能添加或更新");
              return;
          }
          try {
              await saveOrUpdateUserApi(this.userState.user);
              this.getUsers(this.paramsState.page);
              this.userState.user = {
                  username: "",
                  nickName: "",
                  password: "",
              };
              this.userState.dialogUserVisible = false;
              this.userState.dialogUserVisible2 = false;
          } catch (error) {
              this.userState.dialogUserVisible = false;
              this.userState.dialogUserVisible2 = false;
              console.log(error)
          }
      },
      //删除某个用户
      async removeUser(id) {
          // console.log(id)
          //向服务器发送请求
          await removeUserApi(id);
              //重新发送请求刷新页面
              this.getUsers();
          this.dialogFormVisible = false;
          if (this.tableState.users.length === 1) {
              const page = this.paramsState.page - 1
              this.getUsers(page)
          } else {
              this.getUsers(this.paramsState.page)
          }
      },
      // 修改某个用个用户的信息
      showUpdateUser(user) {
          this.userState.user = { ...user };
          this.userState.dialogUserVisible2 = true;
      },
      //给用户设置角色
      //显示指定角色的信息
      showAssignRole(user) {
          this.userState.user = user;
          this.roleState.dialogRoleVisible = true;
          this.getRoles();
      },
      resetRoleData() {
          Object.assign(this.roleState, {
              dialogRoleVisible: false,
              allRoles: [],
              userRoleIds: [],
              isIndeterminate: false,
              checkAll: false,
          });
      },
      handleCheckAllChange(value) {
          if (value) {
              this.roleState.userRoleIds = this.roleState.allRoles.map((item) => item.id)
          } else {
              this.roleState.userRoleIds = []
          }
          // 如果当前不是全选也不全不选时, 指定为false
          this.roleState.isIndeterminate = false;
      },
      handleCheckedChange() {
          const { userRoleIds, allRoles } = this.roleState;
          this.roleState.checkAll =
              userRoleIds.length === allRoles.length && allRoles.length > 0;
          this.roleState.isIndeterminate =
              userRoleIds.length > 0 && userRoleIds.length < allRoles.length;
      },
      async assignRole() {
          const userId = this.userState.user.id;
          const roleIds = this.roleState.userRoleIds.join(",");
          await assignUserRoleListApi(userId, roleIds);
          this.resetRoleData();
      },
      //获取用户的角色列表
      async getRoles() {
          const result = await getUserRoleListApi(this.userState.user?.id);
          this.roleState.allRoles = result.data.allRolesList;
          this.roleState.userRoleIds = result.data.assignRoles.map((item) => item.id);

          this.roleState.checkAll = result.data.allRolesList.length === result.data.assignRoles.length;
          this.roleState.isIndeterminate =
              result.data.assignRoles.length > 0 && result.data.assignRoles.length < result.data.allRolesList.length;
      }

  },
  mounted() {
      //初始化时获取用户信息
      this.getUsers()
  }
}
</script>

<style lang="scss">
.box {
  padding: 10px;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}
</style>